package com.pai4j.pgc.service.permission;
import com.pai4j.common.enums.RoleCodeEnum;
import com.pai4j.pgc.dao.community.ICoderUtilUserDAO;
import com.pai4j.pgc.entity.community.UserEntity;
import com.pai4j.remote.user.UserServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @Author: 程序员七七
 * @Date: 27.11.21 12:08 上午
 */
@Slf4j
@Service
public class RoleService {

    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private ICoderUtilUserDAO userDAO;

    /***
     * 校验用户是否拥有权限
     * @param userId   用户ID
     * @param roleCode 权限CODE
     * @return
     */
    public boolean hasRole(String userId, Integer roleCode) {
        if (StringUtils.isBlank(userId) || roleCode == null) {
            log.error("{} not has role: {}!", userId, roleCode);
            return false;
        }
        UserEntity userEntity = userServiceClient.getUserEntityFromCache(userId);
        return roleCode.equals(userEntity.getRoleCode());
    }

    /***
     * 查询所有的系统管理员用户id
     * @return
     */
    public Set<String> getSuperAdministratorUserIds() {
        return getUserIdSetByRoleCode(RoleCodeEnum.ADMIN.getCode());
    }

    public boolean isAdmin(String userId) {
        return getSuperAdministratorUserIds().contains(userId);
    }

    /***
     * 取相关角色的用户id
     * @param roleCode
     * @return
     */
    public Set<String> getUserIdSetByRoleCode(Integer roleCode) {
        return userDAO.findAllUserIdByRoleCode(roleCode);
    }
}
